package cn.chencaiju.day09;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

public class KeyWordTest {
	/**
	 * 计算某一文件的中Java关键子出现的次数
	 * @return
	 */
	public Map<String,Integer> getKeyWordFromFile(){
		String uri="E:\\camp\\camp\\code\\src\\cn\\chencaiju\\day08\\Car.java";
		List<String> lines=null;
		try {
			//Files.readAllLines(path)逐行读取文件内容
			lines=Files.readAllLines(Paths.get(uri));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}		
		if(lines==null)return null;
		Map<String,Integer> result=new HashMap<>();
		Set<String> keyWord=new HashSet<String>();
		for(String temp:getKeyWord()) {
			keyWord.add(temp);
		}
		for(String line:lines) {
			String[] str=line.split("[ \t.?;()<>]");
			for(String temp:str) {
				if(keyWord.contains(temp)) {
					if(result.containsKey(temp)) {
						result.put(temp, result.get(temp)+1);
					}else {
						result.put(temp, 1);
					}
				}
			}
		}
		return result;
		
	}
	
	/**
	 * 获取常见的关键字
	 * @return
	 */
	public String[] getKeyWord() {
		String str="private protected public abstract class extends final implements interface native new\r\n" + 
				"static strictfp synchronized transient volatile break continue return do while if else for instanceof switch\r\n" + 
				"case default import package boolean byte char double float int long short null true false\r\n" + 
				"super this void";
		String[] result=str.split("[ ]");
		return result;
		
	}
	@Test public void testKeyWord() {
		Map<String,Integer> map=getKeyWordFromFile();
		Set<Entry<String, Integer>> entrySet = map.entrySet();
		for(Entry<String, Integer> itemp:entrySet) {
			System.out.println(itemp.getKey()+"\t"+itemp.getValue());
		}
	}
}
